Algorithms
1. Linear Search
Step-by-step explanation:
- Start from the first element of the array
- Compare each element with the target value
- If element matches the target, return its index
- If end of array is reached without finding target, return -1
Time: O(n)
Space: O(1)
2. Binary Search
Step-by-step explanation:
- Array must be sorted
- Find the middle element of the array
- If middle element equals target, return its index
- If target is less than middle, search left half
- If target is greater than middle, search right half
- Repeat until found or search space is empty
Time: O(log n)
Space: O(1)
3. Bubble Sort
Step-by-step explanation:
- Start from the first element
- Compare adjacent elements
- Swap if they are in wrong order
- Repeat for each pair of adjacent elements
- Continue passes until no swaps are needed
Time: O(n²)
Space: O(1)
4. Selection Sort
Step-by-step explanation:
- Find the minimum element in the unsorted portion
- Swap it with the first unsorted element
- Move the boundary between sorted and unsorted one element forward
- Repeat until entire array is sorted
Time: O(n²)
Space: O(1)
5. Insertion Sort
Step-by-step explanation:
- Start with the second element as the key
- Compare key with elements in sorted portion
- Shift elements greater than key to the right
- Insert key in its correct position
- Repeat for all elements
Time: O(n²)
Space: O(1)
6. Merge Sort
Step-by-step explanation:
- Divide the array into two halves
- Recursively sort each half
- Merge the two sorted halves
- Compare elements from both halves and place smaller one first
- Continue until all elements are merged
Time: O(n log n)
Space: O(n)
7. Quick Sort
Step-by-step explanation:
- Choose a pivot element
- Partition the array around the pivot
- Elements less than pivot go to left, greater to right
- Recursively apply to left and right partitions
- Combine results
Time: O(n log n)
Space: O(log n)
8. Factorial (Recursive)
Step-by-step explanation:
- Base case: if n = 0 or 1, return 1
- Recursive case: return n * factorial(n-1)
- Each recursive call reduces n by 1
- Stack builds up until base case is reached
- Then stack unwinds, multiplying results
Time: O(n)
Space: O(n)
9. Fibonacci Sequence
Step-by-step explanation:
- Base cases: F(0) = 0, F(1) = 1
- Recursive case: F(n) = F(n-1) + F(n-2)
- Each number is sum of two preceding ones
- Sequence: 0, 1, 1, 2, 3, 5, 8, 13, ...
Time: O(2^n)
Space: O(n)
10. Finding Maximum Element
Step-by-step explanation:
- Initialize max with first element
- Iterate through each element
- Compare current element with max
- If current element > max, update max
- Continue until end of array
- Return max value
Time: O(n)
Space: O(1)